import { Component, OnInit } from '@angular/core';
import { ActivatedRoute } from '@angular/router';
import { MatIconRegistry } from "@angular/material/icon";
import { DomSanitizer } from "@angular/platform-browser";
import { EChartsOption } from 'echarts';
import { FormBuilder, FormGroup } from '@angular/forms';
import { RunData, EQData } from 'src/app/model/site-summary/index-interface';
import { ExcelService } from 'src/app/services/excel.service';
import { MatDatepickerInputEvent } from '@angular/material/datepicker';
import { SiteListService } from 'src/app/services/site-list.service';
import { MatSnackBar } from '@angular/material/snack-bar';
import { ImportElectrovalenceInterface } from 'src/app/model';





@Component({
  selector: 'app-site-list',
  templateUrl: './site-list.component.html',
  styleUrls: ['./site-list.component.scss']
})
export class SiteListComponent implements OnInit {

  /** 站点ID，路由传过来的值 */
  id!: number;
  /** 饼图Option */
  chartOptionPie: EChartsOption = {
    legend: {
      show: false
    },
    series: [
      {
        name: 'Nightingale Chart',
        type: 'pie',
        radius: [10, 100],
        center: ['50%', '50%'],
        width: '100%',
        itemStyle: {
          borderRadius: 5
        },
        label: {  //是否展示扇形对应的标签
          show: true
        },
        data: [
          { value: 40, name: 'rose 1' },
          { value: 38, name: 'rose 2' },
          { value: 32, name: 'rose 3' },
          { value: 30, name: 'rose 4' },
          { value: 28, name: 'rose 5' },
          { value: 26, name: 'rose 6' },
          { value: 22, name: 'rose 7' },
          { value: 18, name: 'rose 8' }
        ]
      }
    ]
  };

  /** 线图 */
  optionLine: EChartsOption = {
    xAxis: {
      type: 'category',
      data: ['Mon', 'Tue', 'Wed', 'Thu', 'Fri', 'Sat', 'Sun']
    },
    yAxis: {
      type: 'value'
    },
    series: [
      {
        data: [150, 230, 224, 218, 135, 147, 260],
        type: 'line'
      }
    ]
  };

  /** 时间选择器 */
  range!: FormGroup;

  /** 半环图 */
  realtimeData: RunData = {
    'id': "11223333",
    "发送时间": new Date,
    "SOC": 77,
    "SOH": 91,
    "循环周次": 502,
    "电压": 5.7,
    "电流": 62,
    "速度": 48.5,
    "环境温度": 6.6,
    "lng": 121.7971,
    "lat": 45.9837,
    "speed": 31.3,
    "gpa_lasttime": new Date,
    "temper": [38.8, 41.2, 21.2, 48.9],
    "eq_data": [
      3141, 3132, 3105, 3166, 3153, 3142, 3116, 3112, 3153, 3160, 3100, 3130, 3117, 3154, 3192, 3199
    ],
    "eq_state": "1000110100100100",
    "signals": { "发送时间": new Date, "WIFI": 67, "蓝牙BT": 77, "5G": 84, "4G": 73, "GPRS": 53, "GPS": 10 }
  }

  /** 电池图 */
  eqdata: EQData[] = [
    { series: 1, voltage: 3.212, eqoff: true },
    { series: 2, voltage: 3.244, eqoff: true },
    { series: 3, voltage: 3.234, eqoff: true },
    { series: 4, voltage: 3.223, eqoff: true },
    { series: 5, voltage: 3.224, eqoff: true },
    { series: 6, voltage: 3.242, eqoff: true },
    { series: 7, voltage: 3.245, eqoff: true },
    { series: 8, voltage: 3.244, eqoff: true },
    { series: 9, voltage: 3.255, eqoff: true },
    { series: 10, voltage: 3.256, eqoff: true },
    { series: 11, voltage: 3.241, eqoff: true },
    { series: 12, voltage: 3.356, eqoff: true },
    { series: 13, voltage: 3.232, eqoff: true },
    { series: 14, voltage: 3.140, eqoff: false },
    { series: 15, voltage: 3.222, eqoff: true },
    { series: 16, voltage: 3.321, eqoff: true },
  ]


  /** 导入电价表 */
  electrovalenceExcelData!: ImportElectrovalenceInterface[];
  displayedColumns: string[] = ['status', 'begin', 'electrovalence', 'function'];


  constructor(
    private route: ActivatedRoute,
    private matIconRegistry: MatIconRegistry,
    private domSanitizer: DomSanitizer,
    private fb: FormBuilder,
    private excelService: ExcelService,
    private siteListService: SiteListService,
    private snackBar: MatSnackBar
  ) {
    this.matIconRegistry.addSvgIcon('accumulator', this.domSanitizer.bypassSecurityTrustResourceUrl('assets/svg/accumulator.svg'));
    this.matIconRegistry.addSvgIcon('dtu-eq-on', this.domSanitizer.bypassSecurityTrustResourceUrl('assets/svg/icon-eq-on.svg'));
    this.matIconRegistry.addSvgIcon('dtu-eq-off', this.domSanitizer.bypassSecurityTrustResourceUrl('assets/svg/icon-eq-off.svg'));
  }

  ngOnInit(): void {
    /** 观察路由参数变化，重新获取数据 */
    this.route.params.subscribe(data => {
      this.id = data['id'];
      console.log(this.id)
      this.getSiteDetail();
    })

    /** 日期选择器表单 */
    this.range = this.fb.group({
      start: [{ value: null, disabled: true }],
      end: [{ value: null, disabled: true }]
    })

    this.getPieData();
    this.getHealthData();
  }

  /** 获取站点信息 */
  async getSiteDetail() {
    console.log(1)
    // let res = await this.siteListService.getSiteDetail()
    // this.chartOptionPie = res.data
  }

  /** 储能效益统计饼图数据 */
  getPieData() {
    // let res = await this.siteListService.getPieData()
  }

  /** 获取站点储能系统告警和健康状态数据 */
  getHealthData() {

  }

  /** 日期选择器变化，触发接口请求，刷新数据 */
  dateChange(str: string, event: MatDatepickerInputEvent<Date>) {
    this.getSiteDetail();
    this.getPieData();
    this.getHealthData();
  }


  /** 导入文件 */
  async importFile(e: Event) {
    const f = e.target as HTMLInputElement;
    if (f.files) {
      const file = f.files[0];
      f.value = ''; // 解决上传同个文件失效
      const type = file.name.split('.')[1];
      if (type !== 'xls' && type !== 'xlsx' && type !== 'csv') {
        this.snackBar.open('请上传xls、xlsx、csv格式文件!');
        return;
      }
      // 读取文件
      let result = await this.excelService.read(file, { header: ['status', 'begin', "electrovalence", "function"] });
      if (result[0].status !== '状态' || result[0].begin !== '开始' || result[0].electrovalence !== '电价' || result[0].function !== '执行指令') {
        this.snackBar.open('表头不对应，请下载模板文件编写!');
        return;
      }
      // this.excelService.export(result, "测试文件");
      result.shift();
      result.forEach((item: any) => {
        item.disabled = true;
      });

      this.electrovalenceExcelData = result;
      // let successOrNot = await this.siteListService.exportElectrovalenceExcel();
      // if (successOrNot) {
      //   this.snackBar.open('上传电价成功！');
      // }
      console.log(result);
    }
  }


  save(element: any) {
    console.log(this.electrovalenceExcelData)

    // let successOrNot = await this.siteListService.exportElectrovalenceExcel(this.electrovalenceExcelData);
    // if (successOrNot) {
    //   this.snackBar.open('修改电价成功！');
    // }
  }


  exportExcelFile() {
    let data = [
      { 状态: '谷', 开始: '', 电价: '', 执行指令: '' },
      { 状态: '平', 开始: '', 电价: '', 执行指令: '' },
      { 状态: '峰', 开始: '', 电价: '', 执行指令: '' },
      { 状态: '谷', 开始: '', 电价: '', 执行指令: '' },
      { 状态: '平', 开始: '', 电价: '', 执行指令: '' },
      { 状态: '峰', 开始: '', 电价: '', 执行指令: '' },
    ]
    this.excelService.export(data, "测试文件");
  }
}
